package xyj.sparrow.common.netty.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import xyj.sparrow.common.netty.util.ProtostuffUtil;

/**
 * @ClassName ProtostuffDecoder
 * @Description TODO
 * @Author Jim
 * @Date 2021/1/15 21:16
 * @Version 1.0.0
 **/
public class ProtostuffDecoder extends LengthFieldBasedFrameDecoder {

    public ProtostuffDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {

        int i = in.readableBytes();
        ByteBuf byteBuf = (ByteBuf) super.decode(ctx, in);
        if (byteBuf == null) return null;
        byte[] dst = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(dst);
        return ProtostuffUtil.deserialize(dst);

    }
}
